//
//  GPRefreshHeaderView.m
//  Gruphoto
//
//  Created by Thao Nguyen Huy on 1/5/13.
//  Copyright (c) 2013 CNC Software. All rights reserved.
//

#import "GPRefreshHeaderView.h"
#import <QuartzCore/QuartzCore.h>

@interface GPRefreshHeaderView ()
- (void)spinWithOptions:(UIViewAnimationOptions)options;
- (void)startSpin;
- (void)stopSpin;
@end

@implementation GPRefreshHeaderView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
		bodyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 4, 26.0f, 75.0f)];
		bodyImageView.contentMode = UIViewContentModeScaleAspectFit;
		bodyImageView.image = [UIImage imageNamed:@"refresh_header.png"];
        CGPoint center = bodyImageView.center;
        center.x = self.center.x;
        bodyImageView.center = center;
		[self addSubview:bodyImageView];
		[bodyImageView release];
        
		spinImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 8, 18, 18)];
		spinImageView.contentMode = UIViewContentModeScaleAspectFit;
		spinImageView.image = [UIImage imageNamed:@"spin_image.png"];
        center = spinImageView.center;
        center.x = self.center.x;
        spinImageView.center = center;
		[self addSubview:spinImageView];
		[spinImageView release];
    }
    return self;
}

- (void)dealloc {
    bodyImageView = nil;
    spinImageView = nil;
    [super dealloc];
}

- (void)spinWithOptions:(UIViewAnimationOptions)options {
    [UIView animateWithDuration: 0.2f
                          delay: 0.0f
                        options: options
                     animations: ^{
                         spinImageView.transform = CGAffineTransformRotate(spinImageView.transform, M_PI / 2);
                     }
                     completion: ^(BOOL finished) {
                         if (finished) {
                             if (animating) {
                                 // if flag still set, keep spinning with constant speed
                                 [self spinWithOptions: UIViewAnimationOptionCurveLinear];
                             } else if (options != UIViewAnimationOptionCurveEaseOut) {
                                 // one last spin, with deceleration
                                 [self spinWithOptions: UIViewAnimationOptionCurveEaseOut];
                             }
                         }
                     }];
}

- (void)startSpin {
    if (!animating) {
        animating = YES;
        [self spinWithOptions: UIViewAnimationOptionCurveEaseIn];
    }
}

- (void)stopSpin {
    // set the flag to stop spinning after one last 90 degree increment
    animating = NO;
}

- (void)toggleSpinImageView:(BOOL)animated {
    if (!animated) {
        [self stopSpin];
    }
    else {
        [self startSpin];
    }
}

@end
